package com.zgh.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgh.domain.*;
import com.zgh.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BbsService {
    @Autowired
    private BbsMapper bbsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BbsCommentMapper bbsCommentMapper;

    @Autowired
    private BbsCollectionMapper bbsCollectionMapper;

    @Autowired
    private ProvinceMapper provinceMapper;

    /**
     * 查询所有论坛
     * @return 论坛集合
     */
    public List<Bbs> getAllBbsByTime(String order,String provinceName) {
        //根据时间获取所有论坛
        QueryWrapper<Bbs> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc(order).eq("provinceName",provinceName);
        List<Bbs> bbsList = bbsMapper.selectList(wrapper);
        //根据论坛userid查询用户信息
        for (Bbs bbs : bbsList) {
            bbs.setUser(userMapper.findUserById(bbs.getUserId()));
        }
        return bbsList;
    }

    /**
     * 根据id查询论坛
     * @param id 论坛id
     * @return 论坛
     */
    public Bbs findBbsById(String id) {
        //条件构造器
        QueryWrapper<Bbs> bbsWrapper = new QueryWrapper<>();
        bbsWrapper.eq("id",id);
        //查询论坛
        Bbs bbs = bbsMapper.selectOne(bbsWrapper);
        //根据论坛userid查询用户信息
        bbs.setUser(userMapper.findUserById(bbs.getUserId()));
        //根据论坛id查询评论
        QueryWrapper<BbsComment> bbsCommentWrapper = new QueryWrapper<>();
        bbsCommentWrapper.eq("bbsId",id);
        List<BbsComment> bbsComments = bbsCommentMapper.selectList(bbsCommentWrapper);
        //根据评论用户id查询用户
        for (BbsComment bbsComment : bbsComments) {
            User user = userMapper.findUserById(bbsComment.getUserId());
            bbsComment.setUser(user);
        }
        bbs.setBbsCommentList(bbsComments);
        System.out.println(bbs);
        return bbs;
    }

    /**
     * 点赞
     * @param bbsId 论坛id
     * @param thumbCount 点赞数
     */
    public void thumb(String bbsId, String thumbCount) {
        int thumb = Integer.parseInt(thumbCount);
        bbsMapper.thumb(bbsId,thumb);
    }

    /**
     * 收藏
     * @param bbsId 论坛id
     * @param openId openid
     * @param operator 操作 0插入 1删除
     */
    public void collect(String bbsId, String openId, String operator) {
        UpdateWrapper<BbsCollection> bbsCollectionUpdateWrapper = new UpdateWrapper<>();
        User user = userMapper.findUserByOpenId(openId);
        if (operator.equals("0")){
            //插入
            BbsCollection bbsCollection = new BbsCollection();
            bbsCollection.setBbsId(Integer.parseInt(bbsId));
            bbsCollection.setUserId(user.getId());
            bbsCollection.setCollectionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            bbsCollectionMapper.insert(bbsCollection);
        }else{
            //删除
            bbsCollectionUpdateWrapper.eq("bbsId",bbsId).eq("userId",user.getId());
            bbsCollectionMapper.delete(bbsCollectionUpdateWrapper);
        }
    }

    /**
     * 获取当前用户的收藏论坛集合
     * @param openId openid
     * @return 收藏集合
     */
    public List<BbsCollection> getBbsCollectList(String openId) {
        User user = userMapper.findUserByOpenId(openId);
        QueryWrapper<BbsCollection> bbsCollectionQueryWrapper = new QueryWrapper<>();
        bbsCollectionQueryWrapper.eq("userId",user.getId());
        return bbsCollectionMapper.selectList(bbsCollectionQueryWrapper);
    }

    /**
     * 根据bbsID查询收藏数量
     * @param bbsId bbsid
     * @return 数量
     */
    public int getCollectCountByBbsId(String bbsId) {
        QueryWrapper<BbsCollection> bbsCollectionQueryWrapper = new QueryWrapper<>();
        bbsCollectionQueryWrapper.eq("bbsId",bbsId);
        return bbsCollectionMapper.selectCount(bbsCollectionQueryWrapper);
    }
    /**
     * 上传话题
     * @param bbs1
     * @return 失败或成功
     */
    public int uploadBbs(Bbs bbs1) {
        String openid = bbs1.getUser().getOpenid();
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new UpdateWrapper<User>().lambda();
        userLambdaUpdateWrapper.eq(User::getOpenid,openid);
        User user1 = userMapper.selectOne(userLambdaUpdateWrapper);
        int userid = user1.getId();
        bbs1.setUserId(userid);
        bbs1.setAuthor(user1.getNickname());
        bbs1.setReleaseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        QueryWrapper<Province> provinceQueryWrapper = new QueryWrapper<>();
        provinceQueryWrapper.eq("province",bbs1.getProvinceName());
        Province province = provinceMapper.selectOne(provinceQueryWrapper);
        bbs1.setProvinceId(province.getId());
        int pd = bbsMapper.insert(bbs1);
        if(pd==1){
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 通过openid查询用户话题
     * @param openId
     * @return 用户话题列表
     */
    public List<Bbs> findBbsByOpenid(String openId) {
        System.out.println(openId);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("openid",openId);
        List<User> userlist = userMapper.selectList(userQueryWrapper);

        User user = userlist.get(0);
        int userId = user.getId();
        QueryWrapper<Bbs> bbsQueryWrapper = new QueryWrapper<>();
        bbsQueryWrapper.eq("userId",userId);
        return bbsMapper.selectList(bbsQueryWrapper);
    }


    /**
     * 分页查询获取所有讨论信息
     * @return bbsList
     */
    public ipageBbs getAllBbsInfo(int page1, int PAGE_RECORDS_NUM, String query) {
        List<Bbs> userList = new ArrayList<Bbs>();
        // 设置条件构造器
        QueryWrapper<Bbs> wrapper = new QueryWrapper<>();
        wrapper.like("title",query);
        // 构造分页信息，其中的Page<>(page, PAGE_RECORDS_NUM)的第一个参数是页数，而第二个参数是每页的记录数
        IPage<Bbs> bbsPage = new Page<>(page1, PAGE_RECORDS_NUM);
        // page(postPage, wrapper)这里的第一个参数就是上面定义了的Page对象，第二个参数就是上面定义的条件构造器对象，通过调用这个方法就可以根据你的分页信息以及查询信息获取分页数据
        IPage<Bbs> bbs1IPage = bbsMapper.selectPage(bbsPage, wrapper);
        // 封装数据，其中getRecords()是获取记录数，getCurrent()获取当前页数，getPages()获取总页数，getTotal()获取记录总数，还要其他更多的方法，大家可以自行查看，在这里就不过多赘述了
        userList = bbs1IPage.getRecords();
        Long total = bbs1IPage.getTotal();
        ipageBbs ipageBbs = new ipageBbs();
        ipageBbs.setBbsList(userList);
        ipageBbs.setTotal(total.intValue());
        return ipageBbs;
    }

    /**
     * 删除通过id论坛
     * @param id
     * @return 是否删除
     */
    public int deleteByid(Integer id) {
        int result = bbsMapper.deleteById(id);
        return result;
    }

    /**
     * 通过bbsId 获取论坛
     * @param id
     * @return 论坛
     */
    public Bbs getBbsById(Integer id) {
        Bbs bbs = bbsMapper.selectById(id);
        return bbs;
    }

    /**
     * 保存论坛信息
     * @param
     * @return
     */
    public int saveInfoByid(Bbs bbs){
        QueryWrapper<Bbs> wrapper = new QueryWrapper<>();
        wrapper.eq("id",bbs.getId());
        Bbs bbs1 = bbsMapper.selectOne(wrapper);
        bbs1.setProvinceName(bbs.getProvinceName());
        bbs1.setTitle(bbs.getTitle());
        bbs1.setAuthor(bbs.getAuthor());
        UpdateWrapper bbsUpdateWrapper = new UpdateWrapper();
        bbsUpdateWrapper.eq("id",bbs.getId());
        return bbsMapper.update(bbs1,bbsUpdateWrapper);
    }

    /**
     * 查询论坛（前三条）
     * @return 集合
     */
    public List<Bbs> getAllBbsByHot(String provinceName) {
        QueryWrapper<Bbs> bbsQueryWrapper = new QueryWrapper<>();
        bbsQueryWrapper.select("id","title","coverUrl","content","thumbs+comments+views as hots","releaseTime");
        if (!"全部".equals(provinceName)){
            bbsQueryWrapper.eq("provinceName",provinceName);
        }
        bbsQueryWrapper.orderByDesc("hots").last("limit 0,3");
        return bbsMapper.selectList(bbsQueryWrapper);
    }


    /**
     * 通过点赞量和搜索词获取话题
     * @return 话题列表
     */
    public List<Bbs> getBbsByValue(String value) {
        QueryWrapper<Bbs> queryWrapper = new QueryWrapper<>();
        if (value!=null){
            queryWrapper.like("title", value);
        }
        queryWrapper.orderByDesc("thumbs");
        List<Bbs> bbsList = bbsMapper.selectList(queryWrapper);
        for (Bbs bbs : bbsList ) {
            User user = userMapper.selectById(bbs.getUserId());
            bbs.setUser(user);
        }
        return bbsList;
    }
    /**
     * 根据用户id查询论坛数量
     * @param userId 用户id
     * @return 数量
     */
    public int getBlogCountById(String userId) {
        QueryWrapper<Bbs> bbsQueryWrapper = new QueryWrapper<>();
        bbsQueryWrapper.eq("userId",userId);
        return bbsMapper.selectCount(bbsQueryWrapper);
    }

    /**
     * 根据用户id查询论坛
     * @param userId 用户id
     * @return 论坛集合
     */
    public List<Bbs> findBbsByUserId(String userId) {
        QueryWrapper<Bbs> bbsQueryWrapper = new QueryWrapper<>();
        bbsQueryWrapper.eq("userId",userId);
        return bbsMapper.selectList(bbsQueryWrapper);
    }
}
